package com.rad.datastat.database;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

import com.rad.datastat.model.AppLaunchInfo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

public class AppLaunchDB {
	public static final String TABLE_NAME = "AppLaunchCount";

	public static final String COL_ID = "_id";
	public static final String COL_PKG_NAME = "pkg_name";
	public static final String COL_LAUNCH_TIME = "launch_time"; // 启动时间 18:06:20
	public static final String COL_DURATION = "duration"; // 持续时间 s
	public static final String COL_DATE = "date"; // 2014-09-30

	private static AppLaunchDB mInstance;
	private DBOpenHelper mDBOpenHelper;
	private ReentrantLock mLock;

	public AppLaunchDB(Context context) {
		mDBOpenHelper = DBOpenHelper.instance(context);
		mLock = mDBOpenHelper.getLock();
	}

	public static synchronized AppLaunchDB instance(Context context) {
		if (mInstance == null) {
			mInstance = new AppLaunchDB(context);
		}

		return mInstance;
	}

	protected static void createTable(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + COL_ID
				+ " integer primary key autoincrement, " + COL_PKG_NAME
				+ " TEXT, " + COL_LAUNCH_TIME + " TEXT, " + COL_DURATION
				+ " INTEGER, " + COL_DATE + " TEXT) ");
	}

	// 保存一条数据
	public boolean save(AppLaunchInfo info) {
		if (info == null) {
			return false;
		}
		if (TextUtils.isEmpty(info.getPkgName())
				|| TextUtils.isEmpty(info.getLaunchTime())) {
			return false;
		}

		SQLiteDatabase db = null;
		try {
			mLock.lock();
			db = mDBOpenHelper.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put(COL_PKG_NAME, info.getPkgName());
			values.put(COL_LAUNCH_TIME, info.getLaunchTime());
			values.put(COL_DURATION, info.getDuration());
			values.put(COL_DATE, info.getDete());

			long ret = db.insert(TABLE_NAME, null, values);

			return ret != -1;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
			mLock.unlock();
		}
		return false;
	}

	// 获取某天之前的日期
	public ArrayList<String> queryDateBeforeDate(String beforeDate) {
		ArrayList<String> ret = new ArrayList<String>();//避免返回为null，减少判断
		SQLiteDatabase db = null;
		Cursor cur = null;
		try {
			mLock.lock();
			db = mDBOpenHelper.getReadableDatabase();
			String[] columns = new String[] { COL_DATE };
			String selection = COL_DATE + "<?";
			String[] selectionArgs = new String[] { beforeDate };

			cur = db.query(true, TABLE_NAME, columns, selection, selectionArgs,
					null, null, null, null);
			for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
				ret.add(cur.getString(cur.getColumnIndex(COL_DATE)));
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null) {
				cur.close();
			}
			if (db != null) {
				db.close();
			}
			mLock.unlock();
		}

		return ret;
	}

	// 获取某天的数据
	public ArrayList<AppLaunchInfo> queryByDate(String date) {
		SQLiteDatabase db = null;
		Cursor cur = null;
		try {
			mLock.lock();
			db = mDBOpenHelper.getReadableDatabase();
			String selection = COL_DATE + "=?";
			String[] selectionArgs = new String[] { date };

			cur = db.query(TABLE_NAME, null, selection, selectionArgs, null,
					null, COL_PKG_NAME);
			ArrayList<AppLaunchInfo> ret = new ArrayList<AppLaunchInfo>();
			for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
				AppLaunchInfo info = new AppLaunchInfo();
				info.setPkgName(cur.getString(cur.getColumnIndex(COL_PKG_NAME)));
				info.setLaunchTime(cur.getString(cur
						.getColumnIndex(COL_LAUNCH_TIME)));
				info.setDuration(cur.getLong(cur.getColumnIndex(COL_DURATION)));
				info.setDete(cur.getString(cur.getColumnIndex(COL_DATE)));
				ret.add(info);
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null) {
				cur.close();
			}
			if (db != null) {
				db.close();
			}
			mLock.unlock();
		}

		return null;
	}

	// 删除某天之前的数据
	public boolean delAllBeforeDate(String beforeDate) {
		SQLiteDatabase db = null;
		try {
			mLock.lock();
			db = mDBOpenHelper.getReadableDatabase();
			String whereClause = COL_DATE + "<?";
			String[] whereArgs = new String[] { beforeDate };
			db.delete(TABLE_NAME, whereClause, whereArgs);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
			mLock.unlock();
		}

		return false;
	}
}
